<template>
	<view class="chat">
		<scroll-view class="scroll" scroll-y show-scrollbar>
			<view class="chat-info" :class="item.sendUser === 0 ? 'chat-self' : 'chat-chatter'"
				v-for="(item, index) in chatLists" :key="index">
				<image :src="item.sendUser === 0 ? user.cover :  spark.cover" mode="aspectFill"
					@click="todetail(item.sendUser,boss.id)"
					style="height: 120rpx; width: 120rpx; border-radius: 50%; margin-right: 15rpx; margin-bottom: auto;">
				</image>
				<view class="chat-message">
					<text class="text-main-xll">{{ item.sendMessage }}</text>
				</view>
			</view>
			<view id="to-buttom" style="height: 12rpx;"></view>
		</scroll-view>
		<view class="input-box">
			<view class="tools">
				<view class="clear" @click="clear">
					<uni-icons type="trash" size="24"></uni-icons>
				</view>
			</view>
			<input type="text" v-model="chatData.sendMessage">
			<button @click="sendToSpark">发送消息</button>
		</view>
		<!-- 带上下文问题(可修改)： -->
		<!-- 		<input v-model="TEXT" style="border: 1px solid gainsboro;" />
		<button style="background-color: blue;color: white;" @click="sendToSpark()">发送给大模型</button>
		<text style="width: 90%;flex-wrap:wrap">{{sparkResult}}</text> -->
	</view>
</template>

<script>
	import * as base64 from "@/utils/base64.js"
	import CryptoJS from '@/utils/crypto-js/crypto-js.js'
	import parser from '@/utils/fast-xml-parser/src/parser'
	import * as utf8 from "@/utils/utf8.js"
	import {
		getTime
	} from '@/utils/getTime.js'
	import {
		config
	} from '@/common/config.js'
	export default {
		name: "spark",
		data() {
			return {
				// TEXT: '你好，我的名字叫大王',
				// APPID: 'd177fd96', // 控制台获取填写
				// APISecret: 'MjY4ZTUzZmJmODY5ZjQ5Y2JkYmVjZTg0',
				// APIKey: 'c4e73a528d2ca5c4b98641579bea0c1f',
				sparkResult: '',
				historyTextList: [], // 历史会话信息，由于最大token12000,可以结合实际使用，进行移出
				tempRes: '', // 临时答复保存
				chatData: {
					bossId: '',
					bossName: '',
					bossImage: '',
					lastMessage: '',
					lastTime: '',
					sendMessage: ''
				},
				chatLists: [],
				spark: {},
				user: {}
			}
		},
		created() {
			uni.setNavigationBarTitle({
				title: "offer小助手"
			});
			uni.setNavigationBarColor({
				frontColor: "#000000",
				backgroundColor: '#00b4b3'
			});
			this.spark = this.$store.state.Spark
			console.log(this.spark)
			this.user.cover = this.$store.state.user.cover
			this.InsertChatList(uni.getStorageSync(this.$store.state.user._id))
		},
		destroyed() {
			uni.setStorageSync(this.$store.state.user._id, this.chatLists)
			uni.closeSocket({})
			console.log("关闭了当前对话...")
		},
		methods: {
			async sendToSpark() {
				if (this.chatData.sendMessage) {
					uni.showToast({
						title: '发送成功!',
						icon: 'none'
					});
					let myUrl = await this.getWebSocketUrl();
					this.tempRes = "";
					// this.sparkResult = "";
					let realThis = this;
					this.socketTask = uni.connectSocket({
						//url: encodeURI(encodeURI(myUrl).replace(/\+/g, '%2B')),
						url: myUrl,
						method: 'GET',
						success: res => {
							console.log(res, "ws成功连接...", myUrl)
							realThis.wsLiveFlag = true;
						}
					})
					realThis.socketTask.onError((res) => {
						console.log("连接发生错误，请检查appid是否填写", res)
					})
					realThis.socketTask.onOpen((res) => {
						this.historyTextList.push({
							"role": "user",
							"content": this.chatData.sendMessage
						})
						// console.info("wss的onOpen成功执行...", res)
						// 第一帧..........................................
						// console.log('open成功...')
						let params = {
							"header": {
								"app_id": config.APPID,
								"uid": "aef9f963-7"
							},
							"parameter": {
								"chat": {
									"domain": "generalv2",
									"temperature": 0.5,
									"max_tokens": 1024
								}
							},
							"payload": {
								"message": {
									"text": this.historyTextList
								}
							}
						};

						let chat_self = {
							sendUser: 0,
							sendMessage: this.chatData.sendMessage
						}
						this.chatLists.push(chat_self);
						this.chatData.lastTime = getTime();
						this.chatData.sendMessage = '';

						realThis.socketTask.send({ // 发送消息，，都用uni的官方版本
							data: JSON.stringify(params),
							success() {
								console.log('第一帧发送成功')
							}
						});
					});

					// 接受到消息时
					var message = ''
					realThis.socketTask.onMessage((res) => {
						// console.log('收到API返回的内容：', res.data);
						let obj = JSON.parse(res.data)
						// console.log("我打印的"+obj.payload);
						let dataArray = obj.payload.choices.text;
						for (let i = 0; i < dataArray.length; i++) {
							realThis.sparkResult = realThis.sparkResult + dataArray[i].content
							realThis.tempRes = realThis.tempRes + dataArray[i].content
						}
						// realThis.sparkResult =realThis.sparkResult+ 
						let temp = JSON.parse(res.data)
						// console.log("0726",temp.header.code)
						message += temp.payload.choices.text[0].content

						if (temp.header.code !== 0) {
							// console.log(`${temp.header.code}:${temp.message}`);
							realThis.socketTask.close({
								success(res) {
									console.log('关闭成功', res)
									realThis.wsLiveFlag = false;
								},
								fail(err) {
									console.log('关闭失败', err)
								}
							})
						}
						if (temp.header.code === 0) {
							if (res.data && temp.header.status === 2) {
								realThis.sparkResult = realThis.sparkResult +
									"\r\n**********************************************"
								this.historyTextList.push({
									"role": "assistant",
									"content": this.tempRes
								})


								realThis.socketTask.close({
									success(res) {
										console.log('关闭成功', res)
									},
									fail(err) {
										// console.log('关闭失败', err)
									}
								})

								console.log("message:" + message)
								let chat_chatter = {
									sendUser: 1,
									sendMessage: message
								}
								this.chatLists.push(chat_chatter);

								this.chatData.lastMessage = message;
								this.chatData.lastTime = getTime();
								// console.log(this.chatList)


							}
						}

					})

				} else {
					uni.showToast({
						title: '请在输入框内填写内容...',
						icon: 'none'
					});
				}
			},
			// 鉴权
			getWebSocketUrl() {
				return new Promise((resolve, reject) => {
					// https://spark-api.xf-yun.com/v1.1/chat  V1.5 domain general
					// https://spark-api.xf-yun.com/v2.1/chat  V2.0 domain generalv2
					var url = "wss://spark-api.xf-yun.com/v2.1/chat";
					var host = "spark-api.xf-yun.com";
					var apiKeyName = "api_key";
					var date = new Date().toGMTString();
					var algorithm = "hmac-sha256";
					var headers = "host date request-line";
					var signatureOrigin = `host: ${host}\ndate: ${date}\nGET /v2.1/chat HTTP/1.1`;
					var signatureSha = CryptoJS.HmacSHA256(signatureOrigin, config.APISecret);
					var signature = CryptoJS.enc.Base64.stringify(signatureSha);
					var authorizationOrigin =
						`${apiKeyName}="${config.APIKey}", algorithm="${algorithm}", headers="${headers}", signature="${signature}"`;
					var authorization = base64.encode(authorizationOrigin);
					url = `${url}?authorization=${authorization}&date=${encodeURI(date)}&host=${host}`;

					// console.log(url)
					resolve(url); // 主要是返回地址
				});
			},
			clear() {
				this.chatLists = []
				uni.showToast({
					title: '聊天记录已删除',
					icon: 'none'
				});
			},
			InsertChatList(List) {
				for (let i = 0; i < List.length; i++) {
					this.chatLists.push(List[i])
				}
			}
		}
	}
</script>

<style lang="scss">
	.chat {
		background: gainsboro;
		width: 100%;

		.scroll {
			height: 88vh;

			.chat-info {
				display: flex;
				align-items: center;
				margin-bottom: 12rpx;

				.chat-message {
					max-width: 60%;
					padding: 15rpx;
					font-weight: bold;
					border-radius: 15rpx;
					box-shadow: rgba(60, 64, 67, 0.3) 0rpx 1rpx 2rpx 0rpx, rgba(60, 64, 67, 0.15) 0rpx 1rpx 3rpx 1rpx;
				}
			}

			.chat-chatter {
				margin-left: 15rpx;

				.chat-message {
					background-image: linear-gradient(-225deg, #fffeff 0%, #d7fffe 100%);
				}
			}

			.chat-self {
				flex-direction: row-reverse;
				margin-left: auto;

				.chat-message {
					margin: 10rpx;
					background-image: linear-gradient(-20deg, #e9defa 0%, #fbfcdb 100%);
				}

			}


		}

		.input-box {
			position: fixed;
			z-index: 99;
			bottom: 0;
			width: 100%;
			height: 6%;
			padding: 10px;
			display: flex;
			flex-direction: row;
			align-items: center;
			background: white;

			.tools {
				background: red;
				height: 6vh;
				z-index: 99;
				width: 10vw;
				border-radius: 20rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			input {
				width: 60%;
				border: 1px solid black;
				border-radius: 20px;
				height: 50%;
				padding: 5px 5px 5px 15px;
				background: white;
				margin-left: 20rpx;
			}

			button {
				position: relative;
				margin-right: 18px;
				width: 18vw;
				height: 6vh;
				border-radius: 20rpx;
				background: $boss-base-color;
				text-align: center;
				// align-items: center;
			}
		}
	}
</style>